package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Material;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

import java.util.List;

@SuppressWarnings("JpaQlInspection")
public class MaterialsDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public List<Material> getAllMaterials()
    {
        Session session = sessionFactory.openSession();

        List<Material> materials = session.createCriteria(Material.class)
                .list();

        session.close();

        return materials;
    }

    public Material addMaterial(String name)
    {
        Material material = new Material();
        material.setName(name);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(material);

        tx.commit();
        session.close();

        return material;
    }

    public Material editMaterial(Integer id, Material material) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Material materialToEdit = (Material) session.get(Material.class, id);

        if(materialToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        materialToEdit.setName(material.getName());
        session.update(materialToEdit);
        tx.commit();
        session.close();

        return materialToEdit;
    }

    public void deleteMaterial(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Material where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
